<template>
  <div class="app-container">
    <template v-if="device === DeviceEnum.MOBILE">
      <div class="mobile-header">
        <svg-icon icon-class="contract" size="18px" @click="showMobileDrawer = true"/>
        <div class="conversation-title">{{ currentConversationInfo?.conversationInfo.title }}</div>
        <svg-icon icon-class="ai-add-conversation" size="18px" @click="handleNewConversation"/>
      </div>
    </template>
    <div class="chat-layout">
      <template v-if="device !== DeviceEnum.MOBILE">
        <div class="sidebar-col">
          <conversation-container
              :conversation-groups="conversationGroups"
              :conversation-id="currentConversationId"
              :draft-conversation-id="draftConversationId"
              @new="handleNewConversation"
              @active="handleActive"
              @delete="handleDelete"
              @rename="handleRename"
              @delete-group="handleDeleteGroup"
          />
        </div>
      </template>
      <div class="main-col">
        <chat-container
            v-model:current-conversation-info="currentConversationInfo"
            v-model:message="message"
            :conversation-id="currentConversationId"
            :device="device"
            @messageSent="loadConversation"
            @loadConversation="loadConversation"
            @titleShouldUpdate="handleTitleShouldUpdate"
        />
      </div>
    </div>
    <el-drawer
        v-if="device === DeviceEnum.MOBILE"
        v-model="showMobileDrawer"
        :with-header="false"
        direction="ltr"
        size="80%"
    >
      <conversation-container
          :conversation-groups="conversationGroups"
          :conversation-id="currentConversationId"
          :draft-conversation-id="draftConversationId"
          @new="handleNewConversation"
          @active="handleActive"
          @delete="handleDelete"
          @rename="handleRename"
          @delete-group="handleDeleteGroup"
      />
    </el-drawer>
  </div>
</template>

<script lang="ts" setup>
import {DeviceEnum} from "@/enums/DeviceEnum";
import {UserChatConversationDetailVO, UserChatConversationVO, UserChatMessageVO} from "@/api/ai/chat/user-chat/type";
import {useSystemStore} from "@/store/modules/system";
import {UserChatAPI} from "@/api/ai/chat/user-chat";
import {dayjs} from "element-plus";

// 组件名
defineOptions({
  name: "DeepSeek",
  inheritAttrs: false,
});

// 数据
const currentConversationId = ref<string>("");
const draftConversationId = ref<string>("");
const currentConversationInfo = ref<UserChatConversationDetailVO>();
const device = computed(() => useSystemStore().app.device);
const showMobileDrawer = ref(false);
const message = ref<UserChatMessageVO[]>([]);
const conversationGroups = ref<{ title: string; items: UserChatConversationVO[] }[]>([]);
const conversationPageQuery = ref({
  title: undefined,
  pageNum: 1,
  pageSize: 30,
});

// 加载会话并分组
async function loadConversation() {
  await UserChatAPI.CONVERSATION_PAGE.request(conversationPageQuery.value).then(({data: conversations}) => {
    const currentDate = dayjs().startOf('day');
    const tempMap = new Map<string, UserChatConversationVO[]>();
    conversations.list.forEach((conversation: UserChatConversationVO) => {
      const itemDate = dayjs(conversation.lastActiveTime).startOf('day');
      const diffDays = currentDate.diff(itemDate, 'day');
      let title = '';
      if (diffDays === 0) {
        title = '今天';
      } else if (diffDays === 1) {
        title = '昨天';
      } else if (diffDays >= 2 && diffDays <= 7) {
        title = '7天内';
      } else if (diffDays >= 8 && diffDays <= 30) {
        title = '30天内';
      } else {
        title = itemDate.format('YYYY-MM-DD');
      }
      if (!tempMap.has(title)) {
        tempMap.set(title, []);
      }
      tempMap.get(title)?.push(conversation);
    });
    conversationGroups.value = Array.from(tempMap.entries()).map(([title, items]) => ({title, items}));
    if (currentConversationId.value === draftConversationId.value) {
      draftConversationId.value = "";
    }
  });
}

// 新建会话
async function handleNewConversation() {
  if (draftConversationId.value === "") {
    await UserChatAPI.DRAFT_CONVERSATION.request().then(({data}) => {
      currentConversationId.value = data;
      draftConversationId.value = data;
    });
  } else {
    currentConversationId.value = draftConversationId.value;
  }
}

// 激活会话
function handleActive({groupTitle, itemId}: { groupTitle: string, itemId: string }) {
  currentConversationId.value = itemId;
}

// 删除会话
async function handleDelete({groupTitle, itemId}: { groupTitle: string, itemId: string }) {
  await UserChatAPI.DELETE_CONVERSATION.request([itemId]);
  if (currentConversationId.value === itemId) {
    await handleNewConversation();
  }
  await loadConversation();
}

// 重命名会话
async function handleRename({groupTitle, itemId, newTitle}: { groupTitle: string, itemId: string, newTitle: string }) {
  await UserChatAPI.UPDATE_TITLE.request(itemId, newTitle);
  await loadConversation();
}

// 删除分组
async function handleDeleteGroup({groupTitle}: { groupTitle: string }) {
  const group = conversationGroups.value.find(g => g.title === groupTitle);
  if (!group) return;
  const ids = group.items.map(i => i.id).filter((id): id is string => !!id);
  await UserChatAPI.DELETE_CONVERSATION.request(ids);
  if (ids.includes(currentConversationId.value)) {
    await handleNewConversation();
  }
  await loadConversation();
}

// 监听用户切换会话
watch(currentConversationId, async (newVal, oldVal) => {
  // 刷新 Message 信息
  if (oldVal !== "" && newVal !== "") {
    UserChatAPI.MESSAGE_PAGE.request({
      conversationId: newVal,
      pageNum: 1,
      pageSize: 20
    }).then(({data}) => {
      message.value = data.list;
    });
  }
  // 刷新会话详情
  UserChatAPI.DETAIL.request(currentConversationId.value).then(({data}) => {
    currentConversationInfo.value = data;
  });
});

async function handleTitleShouldUpdate(conversationId: string) {
  const {data: newTitle} = await UserChatAPI.AI_TITLE.request(conversationId);
  await UserChatAPI.UPDATE_TITLE.request(conversationId, newTitle);
  await loadConversation();
}

// 初始化
onMounted(async () => {
  await handleNewConversation();
  await loadConversation();
});

</script>

<style lang="scss" scoped>
.app-container {
  height: 100%;
}

.chat-layout {
  display: flex;
  height: 100%;
  width: 100%;
}

:deep(.el-drawer__body) {
  padding: 0;
}

@media (max-width: 768px) {
  .chat-layout {
    display: flex;
    height: 95%;
  }
  .mobile-header {
    height: 5%;
  }
}

.mobile-header {
  padding: 0 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 30px;

  .conversation-title {
    font-size: 16px;
    color: #333;
    font-weight: 500;
    flex: 1;
    text-align: center;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    display: block;
  }
}

.sidebar-col {
  height: 100%;
  transition: width 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  box-shadow: 2px 0 8px 0 rgba(0, 0, 0, 0.03);
  overflow: hidden;
  z-index: 2;
}

.main-col {
  flex: 1 1 0;
  height: 100%;
  min-width: 0;
  transition: background 0.2s;
  overflow: auto;
}
</style>
